package com.yihu.wlyy.web.patient.health;

import java.util.Iterator;
import java.util.List;

import com.yihu.wlyy.health.entity.DevicePatientHealthIndex;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihu.wlyy.entity.patient.PatientHealthStandard;
import com.yihu.wlyy.service.app.health.PatientHealthIndexService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.web.BaseController;

@Controller
@RequestMapping(value = "/patient/health_index")
@Api(description = "患者指标")
public class PatientHealthController extends BaseController {

	@Autowired
	private PatientHealthIndexService healthIndexService;

	/**
	 * 患者最近填写的健康指标
	 * @return
	 */
	@RequestMapping(value = "recent")
	@ResponseBody
	public String recent() {
		try {
			JSONArray array = healthIndexService.findRecentByPatient(getUID());
			if (array != null) {
				return write(200, "查询成功", "list", array);
			} else {
				return error(-1, "查询失败");
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败");
		}
	}

	/**
	 * 保存患者健康指标 (旧)
	 * @param intervene 干预标志
	 * @param time 记录时间
	 * @param value1 血糖/收缩压/体重/腰围/早餐前空腹
	 * @param value2 舒张压/早餐后空腹
	 * @param value3 午餐空腹
	 * @param value4 午餐后
	 * @param value5 晚餐空腹
	 * @param value6 晚餐后
	 * @param value7 睡前
	 * @param type 健康指标类型（1血糖，2血压，3体重，4腰围）
	 * @return 操作结果
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	public String add(@RequestParam(required = false) String intervene, String time, String value1, String value2, String value3, String value4, String value5, String value6, String value7, int type) {
		try {

			DevicePatientHealthIndex healthIndex = null;
			if (type == 1) {
				// 血糖等一天只能存在一条数据
				Iterable<DevicePatientHealthIndex> list = healthIndexService.findByPatienDate(getUID(), type, DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
				if (list != null) {
					for (DevicePatientHealthIndex model : list) {
						healthIndex = model;
					}
				}
			}
			if (healthIndex == null) {
				healthIndex = new DevicePatientHealthIndex();
			}
			// 设置患者标识
			healthIndex.setUser(getUID());
			// 设置干预标识，默认为NULL
			healthIndex.setIntervene(intervene);

			int index = 0;
			double value = 0;

			// 设置血糖/收缩压/体重/腰围/早餐前空腹
			if (NumberUtils.toDouble(value1, 0) > 0) {
				healthIndex.setValue1(value1);
				index = 1;
				value = NumberUtils.toDouble(value1, 0);
			}
			// 设置 舒张压/早餐后血糖
			if (NumberUtils.toDouble(value2, 0) > 0) {
				healthIndex.setValue2(value2);
				index = 2;
				value = NumberUtils.toDouble(value2, 0);
			}
			// 设置午餐前血糖
			if (NumberUtils.toDouble(value3, 0) > 0) {
				healthIndex.setValue3(value3);
				index = 3;
				value = NumberUtils.toDouble(value3, 0);
			}
			// 设置午餐后血糖
			if (NumberUtils.toDouble(value4, 0) > 0) {
				healthIndex.setValue4(value4);
				index = 4;
				value = NumberUtils.toDouble(value4, 0);
			}
			// 设置晚餐前血糖
			if (NumberUtils.toDouble(value5, 0) > 0) {
				healthIndex.setValue5(value5);
				index = 5;
				value = NumberUtils.toDouble(value5, 0);
			}
			// 设置晚餐后血糖
			if (NumberUtils.toDouble(value6, 0) > 0) {
				healthIndex.setValue6(value6);
				index = 6;
				value = NumberUtils.toDouble(value6, 0);
			}
			// 设置睡前血糖
			if (NumberUtils.toDouble(value7, 0) > 0) {
				healthIndex.setValue7(value7);
				index = 7;
				value = NumberUtils.toDouble(value7, 0);
			}
			// 设置健康指标类型（1血糖，2血压，3体重，4腰围）
			healthIndex.setType(type);
			// 设置记录时间
			if(type == 2){
				healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
			}else {
				healthIndex.setRecordDate(DateUtil.strToDate(time, DateUtil.YYYY_MM_DD));
			}
			healthIndex.setSortDate(DateUtil.strToDateAppendNowTime(time, DateUtil.YYYY_MM_DD_HH_MM_SS));
			// 保存到数据库
			healthIndex = healthIndexService.save(healthIndex, index, value,getUID());
			if (healthIndex == null) {
				return error(-1, "保存失败！");
			}
			return success("保存成功！");
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "保存失败！");
		}
	}

	@RequestMapping(value = "addPatientHealthIndex",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("新增患者指标")
	public String addPatientHealthIndex(@ApiParam(name="data",value="指标数据",defaultValue = "{\"gi\":\"5.5\",\"gi_type\":\"1\"}")
										@RequestParam(value="data",required = true) String data,
										@ApiParam(name="type",value="指标类型",defaultValue = "1")
										@RequestParam(value="type",required = true) String type)
	{
		try {
			DevicePatientHealthIndex obj = healthIndexService.addPatientHealthIndex(data, type, getUID(), null);
			//血糖和血压需要校验
			if(type.equals("1")||type.equals("2"))
			{
				healthIndexService.verifyHealthIndex(obj.getId());
			}

			return success("新增患者指标成功！");
		}
		catch (Exception ex)
		{
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}


	@RequestMapping(value = "verifyPatientHealthIndex",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("校验患者指标")
	public String verifyPatientHealthIndex(@ApiParam(name="id",value="指标id",defaultValue = "")
										@RequestParam(value="id",required = true) Long id)
	{
		try {
			healthIndexService.verifyHealthIndex(id);

			return success("校验患者指标成功！");
		}
		catch (Exception ex)
		{
			return invalidUserException(ex, -1, ex.getMessage());
		}
	}

	/**
	 * 根据患者标志获取健康指标
	 * @param type 健康指标类型（1血糖，2血压，3体重，4腰围）
	 * @return 操作结果
	 */
	@RequestMapping(value = "chart",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("根据患者标志获取健康指标(图表)")
	public String getHealthIndexChartByPatient(@ApiParam(name="type",value="指标类型",defaultValue = "1")
												   @RequestParam(value="type",required = true) int type,
											   @ApiParam(name="begin",value="开始时间",defaultValue = "2016-08-23 00:00:00")
											   @RequestParam(value="begin",required = true) String begin,
											   @ApiParam(name="end",value="结束时间",defaultValue = "2016-09-23 00:00:00")
												   @RequestParam(value="end",required = true) String end) {
		try {
			List<DevicePatientHealthIndex> list = healthIndexService.findChartByPatien(getUID(), type, begin, end);
			if (list == null) {
				return success("查询成功!");
			}
			JSONArray jsonArray = new JSONArray();
			for (DevicePatientHealthIndex model : list) {
				JSONObject modelJson = new JSONObject();
				modelJson.put("patient", model.getUser());
				modelJson.put("value1", model.getValue1());
				modelJson.put("value2", model.getValue2());
				modelJson.put("value3", model.getValue3());
				modelJson.put("value4", model.getValue4());
				modelJson.put("value5", model.getValue5());
				modelJson.put("value6", model.getValue6());
				modelJson.put("value7", model.getValue7());
				modelJson.put("type", model.getType());
				if(type == 2){
					modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				}else{
					modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
				}
				modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
				jsonArray.put(modelJson);
			}
			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败！");
		}
	}

	/**
	 * 根据患者标志获取健康指标
	 * @param type 健康指标类型（1血糖，2血压，3体重，4腰围）
	 * @param pagesize 页数
	 * @return 操作结果
	 */
	@RequestMapping(value = "list",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("患者获取健康指标")
	public String getHealthIndexByPatient(@ApiParam(name="type",value="指标类型",defaultValue = "1")
										   @RequestParam(value="type",required = true) int type,
										  @ApiParam(name="start",value="开始时间",defaultValue = "2016-07-23 00:00:00")
										  @RequestParam(value="start",required = true) String start,
										  @ApiParam(name="end",value="结束时间",defaultValue = "2016-08-23 00:00:00")
										  @RequestParam(value="end",required = true) String end,
										  @ApiParam(name="page",value="第几页",defaultValue = "1")
										  @RequestParam(value="page",required = true) int page,
										  @ApiParam(name="pagesize",value="每页几行",defaultValue = "10")
										  @RequestParam(value="pagesize",required = true) int pagesize) {
		try {
			List<DevicePatientHealthIndex> list = healthIndexService.findIndexByPatient(getUID(), type, start,end,page, pagesize);

			JSONArray jsonArray = new JSONArray();
			if (list != null) {
				for (DevicePatientHealthIndex model : list) {
					JSONObject modelJson = new JSONObject();
					modelJson.put("id", model.getId());
					modelJson.put("patient", model.getUser());
					modelJson.put("value1", model.getValue1());
					modelJson.put("value2", model.getValue2());
					modelJson.put("value3", model.getValue3());
					modelJson.put("value4", model.getValue4());
					modelJson.put("value5", model.getValue5());
					modelJson.put("value6", model.getValue6());
					modelJson.put("value7", model.getValue7());
					modelJson.put("type", model.getType());
					if(type == 2) {
						modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					}else{
						modelJson.put("date", DateUtil.dateToStr(model.getRecordDate(), DateUtil.YYYY_MM_DD));
					}
					modelJson.put("sortDate", DateUtil.dateToStrLong(model.getSortDate()));
					modelJson.put("czrq", DateUtil.dateToStr(model.getCzrq(), DateUtil.YYYY_MM_DD_HH_MM_SS));
					jsonArray.put(modelJson);
				}
			}

			return write(200, "查询成功", "list", jsonArray);
		} catch (Exception ex) {
			error(ex);
			return invalidUserException(ex, -1, "查询失败！");
		}
	}

	/**
	 * 患者健康指标预警值查询
	 * @return
	 */
	@RequestMapping(value = "standard")
	@ResponseBody
	public String standard() {
		try {
			JSONArray standardArray = new JSONArray();
			JSONArray userArray = new JSONArray();
			Iterable<PatientHealthStandard> iterable = healthIndexService.findStandardByPatient(getUID());
			Iterator<PatientHealthStandard> iterator = null;
			if (iterable != null) {
				iterator = iterable.iterator();
			}
			// 预警值未设置，返回默认值
			StringBuffer sb = new StringBuffer();
			sb.append("[");
			// 默认血糖（餐前，餐后二小时）
			sb.append("{min_value_1:3.9, max_value_1:6.1, min_value_2:4.4, max_value_2:7.8, type:1},");
			// 默认血压（收缩压，舒张压）
			sb.append("{min_value_1:90, max_value_1:139, min_value_2:60, max_value_2:89, type:2}");
			sb.append("]");
			standardArray = new JSONArray(sb.toString());
			if (iterator != null) {
				while (iterator.hasNext()) {
					PatientHealthStandard phs = iterator.next();
					if (phs == null) {
						continue;
					}
					JSONObject json = new JSONObject();
					// 最低安全值(血糖餐前\收缩压\体重\腰围)
					json.put("min_value_1", phs.getMinValue1());
					// 最高安全值(血糖餐前\收缩压\体重\腰围)
					json.put("max_value_1", phs.getMaxValue1());
					// 最低安全值(血糖餐后\舒张压)
					json.put("min_value_2", phs.getMinValue2());
					// 最高安全值(血糖餐后\舒张压)
					json.put("max_value_2", phs.getMaxValue2());
					// 健康指标类型：1血糖，2血压，3体重，4腰围
					json.put("type", phs.getType());
					userArray.put(json);
				}
			}
			JSONObject json = new JSONObject();
			json.put("standard", standardArray);
			json.put("custom", userArray);
			return write(200, "查询成功", "data", json);
		} catch (Exception e) {
			error(e);
			return invalidUserException(e, -1, "查询失败！");
		}
	}
}
